package com.yanqu.road.server.gameplayer.module.cricket.entity.dao;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.dbV2.serializer.Helper;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.logic.model.cricket.CricketUserBaseInfo;
import com.yanqu.road.server.gameplayer.module.cricket.entity.DbUserCricketBattleLog;


import java.sql.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserCricketBattleLogDaoImpl extends TempDataObjectDao<DbUserCricketBattleLog> {


    public static UserCricketBattleLogDaoImpl newInstance() {
        UserCricketBattleLogDaoImpl dao = new UserCricketBattleLogDaoImpl();
        return dao;
    }

    @Override
    protected boolean addData(DbUserCricketBattleLog data) {
        return false;
    }

    @Override
    protected boolean updateData(DbUserCricketBattleLog data) {
        return true;
    }

    public static String insertSql = "insert into `t_u_cricket_battle_log`(userId,battleType,score,battleTimestamp,userBaseInfoList,createTime,updateTime) values (?,?,?,?,?,?,?)";


    public DbUserCricketBattleLog addDataWithAutoIncrement(DbUserCricketBattleLog data) {
        data.setBeginWriteTime();
        ResultSet rs = null;
        PreparedStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getBattleType());
            call.setString(i++, data.getScore());
            call.setLong(i++, data.getBattleTimestamp());
            call.setString(i++, Helper.toJSONString(data.getUserBaseInfoList()));
            call.setLong(i++, data.getCreateTime());
            call.setLong(i++, data.getUpdateTime());
            call.execute();
            rs = call.getGeneratedKeys();
            if (rs != null && rs.next()) {
                data.setId(rs.getInt(1));
                return data;
            }
        } catch (Exception e){
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }


    @Override
    protected DbUserCricketBattleLog parseData(ResultSet rs) throws SQLException {
        DbUserCricketBattleLog data = DbUserCricketBattleLog.getInstance();
        data.setId(rs.getInt("id"));
        data.setUserId(rs.getLong("userId"));
        data.setBattleType(rs.getInt("battleType"));
        data.setScore(rs.getString("score"));
        data.setBattleTimestamp(rs.getLong("battleTimestamp"));
        data.setUserBaseInfoList(Helper.toObject(rs.getString("userBaseInfoList"), new TypeReference<List<CricketUserBaseInfo>>() {
        }));
        data.setCreateTime(rs.getLong("createTime"));
        data.setUpdateTime(rs.getLong("updateTime"));

        return data;
    }


    public Map<Long, DbUserCricketBattleLog> getDataMap(long userId, int limit) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, DbUserCricketBattleLog> dataMap = new ConcurrentHashMap<>();
        String selectSql = "select * from t_u_cricket_battle_log where userId = ? order by createTime desc limit ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(selectSql);
            call.setLong(1, userId);
            call.setInt(2, limit);
            rs = call.executeQuery();
            while (rs.next()) {
                DbUserCricketBattleLog data = parse(rs);
                dataMap.put(data.getId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public boolean saveData(DbUserCricketBattleLog data) {
        if (data.isUpdateOption()) {
            if (data.isNeedInsert()) {
                if (addData(data)) {
                    data.setNeedInsert(false);
                }
            }
        }
        return true;
    }

}
